package org.iabako.client.ui.form.business.sale.make;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.HTMLPanel;
import org.iabako.client.tools.IabakoAsyncCallback;
import org.iabako.client.tools.Messages;
import org.iabako.client.ui.layout.field.LabelText;
import org.iabako.client.ui.layout.field.RadioButtonList;
import org.iabako.client.ui.layout.field.SelectList;
import org.iabako.client.ui.layout.widget.installment.InstallmentsDefinitionForm;
import org.iabako.client.ui.layout.widget.sale.SaleMakeTotalTable;
import org.iabako.client.ui.layout.widget.validation.ValidationMessage;
import org.iabako.shared.entity.business.Installment;
import org.iabako.shared.entity.business.Sale;
import org.iabako.shared.entity.enumeration.*;
import org.iabako.shared.iservice.business.SaleServiceAsync;
import org.iabako.shared.tools.GenericTools;

import java.util.List;

/**
 * Created by jose on 22/10/14.
 */
public class SaleMakePaymentDefinition extends SaleMakeSubForm {

    interface MyUiBinder extends UiBinder<HTMLPanel, SaleMakePaymentDefinition> {
    }

    protected MyUiBinder binderForm = GWT.create(MyUiBinder.class);

    protected final SaleServiceAsync saleServiceAsync = SaleServiceAsync.Util.getInstance();

    @UiField
    RadioButtonList paymentType;
    @UiField
    InstallmentsDefinitionForm installmentsForm;
    @UiField
    LabelText saleNote;
    @UiField
    HTMLPanel paymentTypePanel;
    @UiField
    SelectList paymentMethod;
    @UiField
    SaleMakeTotalTable saleTotalTable;
    @UiField
    HTMLPanel installmentsFormPanel;

    public SaleMakePaymentDefinition() {

        initWidget(binderForm.createAndBindUi(this));

        setDefaultHandlers();
        setPaymentTypeHandler();
        installmentsForm.setSaleNote(saleNote);
    }

    @Override
    protected void restoreDraft() {
        saleTotalTable.taxDisabled = saleMakeForm.saleMakeProductServiceChoice.saleTotalTable.taxDisabled;
        saleTotalTable.calculateAmounts(saleMakeForm.saleMakeProductServiceChoice.ponderedTax, saleMakeForm.saleMakeProductServiceChoice.totalPrice);

        final Sale sale = (Sale) saleMakeForm.entity;
        if (sale.getInstallmentsDefinition() != null && sale.getInstallmentsDefinition().getInstallmentsFrequency() == InstallmentsFrequency.custom) {
            saleServiceAsync.getCustomInstallmentsDefinition((Sale) saleMakeForm.entity, new IabakoAsyncCallback<List<Installment>>() {
                @Override
                public void onSuccess(List<Installment> result) {
                    sale.getInstallmentsDefinition().setInstallments(result);
                    restoreDraftInstallmentsDefinition();
                    super.onSuccess(result);
                }
            });
        } else {
            restoreDraftInstallmentsDefinition();
        }
    }

    private void restoreDraftInstallmentsDefinition() {
        Sale sale = ((Sale) saleMakeForm.entity);

        installmentsForm.totalPrice = saleMakeForm.saleMakeProductServiceChoice.totalPrice;
        installmentsForm.setInstallmentsDefinition(sale.getInstallmentsDefinition());

        if (sale.getInstallmentsDefinition() == null || sale.getInstallmentsDefinition().getInstallmentsType() == InstallmentsType.defined) {
            paymentType.setValue(sale.getPaymentType());
            paymentMethod.setEnumValue(sale.getPaymentMethod());
        } else if (sale.getInstallmentsDefinition().getInstallmentsType() == InstallmentsType.undefined) {
            setUndefinedFields();
        }

        saleMakeForm.saleMakeConfirmation.restoreDraft();
    }

    public void setUndefinedFields() {
        paymentType.setVisible(false);
        paymentMethod.setVisible(false);
        installmentsFormPanel.setVisible(true);
        installmentsForm.installmentsType.setValue(InstallmentsType.undefined);
    }

    private void setPaymentTypeHandler() {
        for (LabelEnum radioKey : paymentType.getRadioButtons().keySet()) {
            if (PaymentType.onePayment.equals(radioKey)) {
                paymentType.getRadioButtons().get(radioKey).addHandler(new ClickHandler() {
                    public void onClick(ClickEvent event) {
                        showPaymentTypeValues(true);
                    }
                }, ClickEvent.getType());
            } else {
                paymentType.getRadioButtons().get(radioKey).addHandler(new ClickHandler() {
                    public void onClick(ClickEvent event) {
                        showPaymentTypeValues(false);
                    }
                }, ClickEvent.getType());
            }
        }
    }

    private void showPaymentTypeValues(boolean onePayment) {
        if (onePayment) {
            paymentMethod.setVisible(true);
            installmentsFormPanel.setVisible(false);
            installmentsForm.installmentsType.setValue(null);

            saleNote.setVisible(true);
            saleNote.setHtmlLabel(Messages.getLabel("sale_make_one_payment_note",
                    GenericTools.formatAmount(saleMakeForm.saleMakeProductServiceChoice.totalPrice + "")));
        } else {
            paymentMethod.setVisible(false);
            installmentsFormPanel.setVisible(true);
            installmentsForm.initializeFields();
        }
    }

    @Override
    protected void validateForm() {
        saleMakeForm.saleWorkflow.getElement().scrollIntoView();

        if (installmentsForm.installmentsType.getValue() == InstallmentsType.defined
                && paymentType.getValue() == null) {
            ValidationMessage.getFirstFromDOM().showErrorMessage(true, true, "validation_sale_make_no_payment_definition_error");
            return;
        }

        if (paymentType.getValue() == PaymentType.onePayment || installmentsForm.handleUiValidation()) {
            saleMakeForm.goTo(SaleStep.confirmation);
            saleMakeForm.saleMakeConfirmation.initialize();
        }
    }

    @Override
    protected void goBackAction() {
        saleMakeForm.goTo(SaleStep.what);
    }
}
